<!doctype html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">




  
  
  <link rel="stylesheet" media="all" href="/lib/Han/dist/han.min.css?v=3.3">




<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Swift," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.1" />






<meta name="description" content="原文链接点击跳转 原文标题是Swift 4 Codable, JSON Handling Made Easy 副标题 Data Can Make You Cry（有没有这么激动） 现在可以用很少的代码实现json的编译与反编译了。虽然有大量的第三方库可以实现该功能，但是Swift系统库也实现了该功能。下面了解一下新的协议。  需求  现在有一个小需求，我们需要发送json数据并释放并释放内存。在S">
<meta name="keywords" content="Swift">
<meta property="og:type" content="article">
<meta property="og:title" content="新的格式化方式">
<meta property="og:url" content="/2017/06/28/新的格式化方式/index.html">
<meta property="og:site_name" content="Maguns‘s Blog">
<meta property="og:description" content="原文链接点击跳转 原文标题是Swift 4 Codable, JSON Handling Made Easy 副标题 Data Can Make You Cry（有没有这么激动） 现在可以用很少的代码实现json的编译与反编译了。虽然有大量的第三方库可以实现该功能，但是Swift系统库也实现了该功能。下面了解一下新的协议。  需求  现在有一个小需求，我们需要发送json数据并释放并释放内存。在S">
<meta property="og:updated_time" content="2017-06-28T13:20:45.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="新的格式化方式">
<meta name="twitter:description" content="原文链接点击跳转 原文标题是Swift 4 Codable, JSON Handling Made Easy 副标题 Data Can Make You Cry（有没有这么激动） 现在可以用很少的代码实现json的编译与反编译了。虽然有大量的第三方库可以实现该功能，但是Swift系统库也实现了该功能。下面了解一下新的协议。  需求  现在有一个小需求，我们需要发送json数据并释放并释放内存。在S">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="/2017/06/28/新的格式化方式/"/>





  <title>新的格式化方式 | Maguns‘s Blog</title>
  














</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Maguns‘s Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">我是一名iOS开发者，初级工程师。</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益404
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="/2017/06/28/新的格式化方式/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Maguns">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="http://oqaxykewn.bkt.clouddn.com/blog_header.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Maguns‘s Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">新的格式化方式</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-06-28T21:18:55+08:00">
                2017-06-28
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Swift/" itemprop="url" rel="index">
                    <span itemprop="name">Swift</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          

          

        </div>
      </header>
    

    <div class="post-body han-init-context" itemprop="articleBody">

      
      

      
        <p>原文链接点击跳转</p>
<p>原文标题是Swift 4 Codable, JSON Handling Made Easy</p>
<p>副标题 Data Can Make You Cry（有没有这么激动）</p>
<p>现在可以用很少的代码实现json的编译与反编译了。虽然有大量的第三方库可以实现该功能，但是Swift系统库也实现了该功能。下面了解一下新的协议。</p>
<ul>
<li>需求</li>
</ul>
<p>现在有一个小需求，我们需要发送json数据并释放并释放内存。在Swift3.0时我们需要写大量的工厂代码去进行编译与反编译。现在，当数据结构需要改变或者必须改变呢？我们需要每次重写代码。</p>
<p>对于如此时尚的语言，有没有更好的解决方式？</p>
<ul>
<li>解决方案<br>Swift给出了更好的解决方案，更好的是，仅需一个字。<br>Codable<br>继承了2个协议的一个字，仅仅需要继承Codable并通过创建的编译或反编译对象，编译器会很优秀的完成映射操作。</li>
<li><p>第一步<br>假设我们有个Person的结构体，需要通过编译器实现结构体到json数据的编译，第一步当然是创建结构体。</p>
<pre><code>Struct Person : Codable{
  enum Gender:String,Codable {
    case Male,Female,Alien
  }
  var name : String
  var userName : String
  var gender:[Gender]
}
</code></pre><p>结构体包含一些变量，像是name,username,gender是一个枚举，用于表示有限的有限制的数据选项。<br>创建一个Person的实例对象</p>
<pre><code>let person = Person(name : &quot;Peter&quot;,userName : &quot;pwitham&quot;,gender :[.Alien])
</code></pre></li>
<li><p>编译为json<br>在实现转化之前，需要创建JSONEncoder实例对象，通过创建的数据对象保存编译实例，这里通过String展示对应的数据</p>
<pre><code>let jsonencoder = JSONEncoder()
let jsonData = jsonencoder.encode(person)
let stringData = String(data : jsonData, encoding : .utf8)
printf(stringData)
</code></pre></li>
<li><p>反编译json<br>在反编译之前，需要创建JSONDecoder实例对象，通过该对象反编译并创建一个容器保存数据。最后打印，查看数据结构</p>
<pre><code>let jsonDecoder = JSONDecoder()
let decodePerson = try jsonDecoder.decoder(Person.self,from:jsonData)
printf(decodePerson)
</code></pre></li>
<li><p>包装<br>现在该协议已经翘首以盼。当修改结构体时，Swift4会自动映射转换成对应的数据结构。</p>
</li>
</ul>
<p>在众多第三方库中，也许这才是最好的选择。</p>
<p>（不是很同意，我使用第三方只是为了比较全面的数据类型转化，鬼知道后台传过来的数据到底是什么格式的）</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Swift/" rel="tag"># Swift</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/06/18/为什么是闭包/" rel="next" title="为什么是闭包">
                <i class="fa fa-chevron-left"></i> 为什么是闭包
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/07/18/CoreAnimation-基础补充/" rel="prev" title="CoreAnimation-基础补充">
                CoreAnimation-基础补充 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      

      <section class="site-overview sidebar-panel sidebar-panel-active">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="http://oqaxykewn.bkt.clouddn.com/blog_header.jpg"
               alt="Maguns" />
          <p class="site-author-name" itemprop="name">Maguns</p>
           
              <p class="site-description motion-element" itemprop="description">其实我有方言的，但更向往普通话。</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives/">
                <span class="site-state-item-count">7</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">4</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">6</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Maguns</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>


        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>


        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.1"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.1"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.1"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.1"></script>



  


  




	





  





  





  






  





  

  

  

  

  

  

</body>
</html>
